import {BaseInterceptor, InterceptorConfig} from './base';

declare const unsafeWindow: Window & typeof globalThis;

export class FetchInterceptor extends BaseInterceptor {
    private readonly originalFetch: typeof fetch;

    constructor(config: InterceptorConfig) {
        super(config);
        this.originalFetch = unsafeWindow.fetch;
    }

    init(): void {
        const self = this;
        console.log('🚀 FetchInterceptor 初始化');

        unsafeWindow.fetch = async function (resource: RequestInfo | URL, init?: RequestInit) {
            console.group('Fetch 请求拦截');

            let finalUrl: string;
            if (typeof resource === 'string') {
                finalUrl = resource;
            } else if (resource instanceof URL) {
                finalUrl = resource.href;
            } else {
                finalUrl = resource.url;
            }

            console.log('原始请求:', finalUrl);

            // 处理 URL 重定向和参数
            const {finalUrl: redirectedUrl, matchedConfig, isRedirected} = self.processUrl(finalUrl);

            // 处理代理
            const proxiedUrl = self.handleProxy(redirectedUrl, isRedirected);

            // 准备请求配置
            init = init || {};
            init.headers = init.headers || {};

            // 添加全局请求头
            const enabledGlobalHeaders = self.getEnabledHeaders(self.config.globalHeaders);
            Object.assign(init.headers, enabledGlobalHeaders);
            console.log('🌍 添加全局请求头:', enabledGlobalHeaders);

            // 添加特定配置的请求头
            if (matchedConfig?.headers) {
                const enabledConfigHeaders = self.getEnabledHeaders(matchedConfig.headers);
                Object.assign(init.headers, enabledConfigHeaders);
                console.log('✌️ 添加配置请求头:', enabledConfigHeaders);
            }

            // 处理请求体
            if (init.body) {
                init.body = self.processRequestBody(init.body, matchedConfig);
            }

            // 更新最终的请求资源
            let finalResource: RequestInfo | URL;
            if (typeof resource === 'string') {
                finalResource = proxiedUrl;
            } else if (resource instanceof URL) {
                finalResource = new URL(proxiedUrl);
            } else {
                finalResource = new Request(proxiedUrl, resource);
            }

            console.log('🔄 最终请求:', proxiedUrl);
            console.groupEnd();

            return self.originalFetch.call(unsafeWindow, finalResource, init);
        };

        console.log('🎉 FetchInterceptor 初始化完成');
    }

    destroy(): void {
        if (this.originalFetch) {
            unsafeWindow.fetch = this.originalFetch;
            console.log('🚪 FetchInterceptor 已销毁');
        }
    }
} 